package com.wanmait.zaisousuo.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmait.zaisousuo.exception.QuestionNotFoundException;
import com.wanmait.zaisousuo.mapper.UserinfoMapper;
import com.wanmait.zaisousuo.pojo.GarbageType;
import com.wanmait.zaisousuo.pojo.Texture;
import com.wanmait.zaisousuo.pojo.Userinfo;
import com.wanmait.zaisousuo.service.QuestionService;
import com.wanmait.zaisousuo.util.Pager;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.omg.CORBA.INTERNAL;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.wanmait.zaisousuo.mapper.QuestionMapper;
import com.wanmait.zaisousuo.pojo.Question;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class QuestionServiceImpl implements QuestionService {

    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private UserinfoMapper userinfoMapper;
    @Resource(name = "questionSolrClient")
    private HttpSolrClient client;

//    添加问题
    @Override
    public void insert(Question object) {

        questionMapper.insert(object);
        userinfoMapper.askCountIncrease(object.getUserinfo().getId());
        
    }

    @Override
    public void update(Question object) {

    }

    @Override
    public void delete(Integer id) {

    }

//    后台批量删除问题
    @Override
    public void delete(String ids) {
        String[] idsStr = ids.split(",");
        List<Integer> idList = new ArrayList<>();
        for (String id : idsStr) {
            idList.add(Integer.parseInt(id));

        }
        questionMapper.deleteAll(idList);
    }

//    通过id查找问题
    @Override
    public Question findById(Integer id) {
        Question question = questionMapper.findById(id);
        if(question==null){
            throw new QuestionNotFoundException(id);
        }
        return question;
    }

//    查找所有问题
    @Override
    @Cacheable(value = "QuestionAnswerCache",key = "'findAllQuestions'")
    public List<Question> findAll() {
       List<Question> questions = questionMapper.findList(null,null);
        return questions;
    }

    @Override
    public List<Question> findAll(Question object) {
        return null;
    }

    @Override
    public int getDataCount() {
        return 0;
    }

    @Override
    public int getDataCount(Question object) {
        return 0;
    }

    @Override
    public PageInfo<Question> findList(int pageNum) {
//        int pageSize=5;
//        PageHelper.startPage(pageNum,pageSize);
//        List<Question> questions = questionMapper.findAll();
//        PageInfo<Question> pageInfo = new PageInfo<>(questions,9);
//        return pageInfo;
        return null;
    }

//    分页查找所有问题
    @Override
    public PageInfo<Question> findList(Integer pageNum, Integer garbageTypeId, Integer textureId) {
        int pageSize=5;
        PageHelper.startPage(pageNum,pageSize);
        List<Question> questions = questionMapper.findList(garbageTypeId,textureId);
        PageInfo<Question> pageInfo = new PageInfo<>(questions,7);
        return pageInfo;
    }

//    后台真删除选中问题
    @Override
    public void realDelete(Integer id) {
        questionMapper.deleteByPrimaryKey(id);
    }

//    后台问题的禁用以及恢复
    @Override
    public Integer updateDisabled(Integer id, boolean disabled) {
        questionMapper.updateDisabled(id,disabled);
        return id;
    }

//    后台批量恢复问题
    @Override
    public void recover(String ids) {
        List<Integer> idList = new ArrayList<>();
        String[] idsStr = ids.split(",");
        for (String id : idsStr) {
            idList.add(Integer.parseInt(id));
        }
        questionMapper.recoverAll(idList);
    }

//    通过时间段查找问题
    @Override
    public List<Question> findByTime(String startTime, String endTime) {
        return questionMapper.findAll(startTime,endTime);
    }

    @Override
    public PageInfo<Question> findByUserId(Integer pageNum, Integer id) {
        Integer pageSize=3;
        PageHelper.startPage(pageNum,pageSize);
        List<Question> questions=questionMapper.findByUserId(id);
        PageInfo<Question> pageInfo= new PageInfo<>(questions);
        return pageInfo;
    }
//    通过solr查找
    @Override
    public List<Question> findQuestion(String keyword, Integer pageNum, Pager pager) {
        SolrQuery query = new SolrQuery();
//  设置查询条件
        if(keyword!=null) {
            query.setQuery("title:" + keyword);
        }
        else{
            query.setQuery("*:*");
        }
        //        设置查询过滤结果


//        query.set
//        设置高亮
        query.setHighlight(true);
//        设置高亮字段
        query.set("hl.fl","title");

//         设置分页
        query.setStart((pager.getPageNum()-1)*pager.getPageSize());
        query.setRows(pager.getPageSize());

//        查询结果
        QueryResponse response = null;
        List<Question> questions = new ArrayList<>();
        Question question=null;
        try {
            response = client.query(query);
            SolrDocumentList documentList = response.getResults();
            Map<String, Map<String,List<String>>> highLighting = response.getHighlighting();
            for (SolrDocument entries : documentList) {
                question = new Question();
                question.setId(Integer.parseInt((String)entries.getFieldValue("id")));
                question.setContent((String)entries.getFieldValue("content"));
                question.setAnswerCount((Integer)entries.getFieldValue("answerCount"));
                question.setFinished((Boolean)entries.getFieldValue("finished"));

                Userinfo userinfo = new Userinfo();
                userinfo.setId(Integer.parseInt((String)entries.getFieldValue("userinfoId")));
                userinfo.setNickname((String)entries.getFieldValue("nickname"));
                question.setUserinfo(userinfo);

                if(keyword==null||keyword==""){
                    question.setTitle((String)entries.getFieldValue("title"));
                }
                else {
                    String id = (String) entries.getFieldValue("id");
                    question.setTitle(highLighting.get(id).get("title").get(0));
                }
                questions.add(question);
            }

        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return questions;
    }

    @Override
    public Integer getDateCount(String keyword, Integer pageNum) {
        SolrQuery query = new SolrQuery();
        //  设置查询条件
        if(keyword!=null) {
            query.setQuery("title:" + keyword);
        }
        else{
            query.setQuery("*:*");
        }
        Integer dateCount = null;
        QueryResponse response = null;
        try {
            response = client.query(query);
            SolrDocumentList documentList = response.getResults();
            dateCount=(int)documentList.getNumFound();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return dateCount;
    }


    //清除ehcache缓存
    @CacheEvict(value = "QuestionAnswerCache",allEntries = true)
    @Override
    public void clearCache() {
    }


}
